from tkinter import filedialog
from datetime import datetime, timezone, timedelta
import math
import simplekml

filepath = filedialog.askopenfilename(filetypes=[('txt', '*.txt'),('dat', '*.dat'),('log', '*.log')])
kml = simplekml.Kml()

def speed_cal(north_speed, east_speed):
    """
        此函数将北向速度和东向速度转换为我们设备的speed，单位换算m/s -> km/h
        :param north_speed: 北向速度m/s
        :param east_speed: 东向速度m/s
        :return: 返回计算的速度值
        """
    speed = math.sqrt(north_speed ** 2 + east_speed ** 2) * 3.6
    return speed

leap_seconds = 18
gps_epoch = datetime(1980, 1, 6)

def gps_to_utc(gps_week, gps_seconds):
    """
    此函数将GPS时间转换为UTC时间。
    :param gps_week: GPS周数
    :param gps_seconds: GPS周内的秒数
    :return: 格式化后的UTC时间字符串，格式为 "%Y%m%d%H%M%S"
    """
    # 计算总的GPS秒数
    total_gps_seconds = gps_week * 7 * 86400 + gps_seconds
    # 减去闰秒得到总的UTC秒数
    total_utc_seconds = total_gps_seconds - leap_seconds
    # 根据GPS起始日期和总的UTC秒数计算UTC时间
    utc_time = gps_epoch + timedelta(seconds=total_utc_seconds)
    # 格式化UTC时间为字符串
    formatted_utc_time = utc_time.strftime("%Y%m%d%H%M%S")
    
    return formatted_utc_time

with open(filepath, 'r', encoding='utf-8') as file:
    lines = file.readlines()

truth_lines = []

for line in lines:
    if '#INSPVAXA' in line:
        parts = line.split(',')
        aligenment_status = parts[9]
        week = float(parts[5])
        seconds = float(parts[6])
        truth_utc_time = gps_to_utc(week, seconds)
        lon_pos = float(parts[12])
        lat_pos = float(parts[11])
        heading = float(parts[20])
        north_speed = float(parts[15])
        east_speed = float(parts[16])
        speed = speed_cal(north_speed, east_speed)  # 调用speed_cal函数将真值速度转换为设备速度
        pos_type = parts[10]

        truth_height = float(parts[13])
        pnt = kml.newpoint(coords=[(lon_pos, lat_pos)],
        description=f"""
            <b>时间:</b> {truth_utc_time}<br/>
            <b>速度:</b> {speed:.2f} m/s<br/>
            <b>方向:</b> {heading:.1f}°<br/>
        """)
        
        truth_lines.append(f"{aligenment_status},{pos_type},{week},{seconds},{truth_utc_time},{heading},{lon_pos},{lat_pos},{speed},{truth_height}\n")

kml.save('truth.kml')
with open('truth_file.txt', 'w', encoding='utf-8') as file:
    file.writelines(truth_lines)


    
